{% extends "memory_base.html" %}
{% load i18n %}
{% block head %}
    <title>{% trans "忆存" %}</title>
    <link href="https://magicbox.bk.tencent.com/static_api/v3/assets/wangEditor-2.1.22/dist/css/wangEditor.min.css" rel="stylesheet">
{#    <link href="https://magicbox.bk.tencent.com/static_api/v3/bk/css-pro/layout/sidebar.css" rel="stylesheet">#}
{#    <link href="https://magicbox.bk.tencent.com/static_api/v3/assets/bk-icon-2.0/iconfont.css" rel="stylesheet">#}
    <link href="https://magicbox.bk.tencent.com/static_api/v3/assets/fontawesome/css/font-awesome.css" rel="stylesheet">
{#    <link href="{{ REMOTE_STATIC_URL }}assets/metisMenu-2.6.0/css/metisMenu.min.css" rel="stylesheet">#}
    <link href="https://magicbox.bk.tencent.com/static_api/v3/components/vertical_nav11/css/index.css" rel="stylesheet">

    {{ block.super }}
    <style>
        .container{
            min-height: 100%;
            background-image: url("{{ STATIC_URL }}memoryImage/background/bigbg2.png");
        }
        .nav-left{
            margin-left: 0px;
        }
        .sidebar {
            width: 250px;
            margin-top: 60px;
            position: relative;
        }
        .right-button-area{
            margin-top: 60px;
        }
        .show-area {

            overflow: hidden;
        }
        #show-memory-content {
            height: 600px;
            overflow-y: scroll;
        }
        #show-memory-content::-webkit-scrollbar {
            display: none;
        }
        #show-memory-title{
            text-align: center;
            font-size: 2.5em;
        }
        .memory-content{
            border: 1px solid #dbdbdb;
            border-radius: 10px;
            background-color: #f0f0f0;
            margin-top: 10px;
            padding: 20px;
            display: none;
        }
        #show-memory-notes{
            text-align: right;
            margin-right: 40px;

        }
        #show-memory-footer {
            margin-top: 20px;
            text-align: center;
            height: auto;
        }
        #edit-memory {
            float: right;
        }
        #show-lockedInfo {
            margin-top: 200px;
            text-align: center;
        }
        .p-note-1{
            font-size: 20px;
        }
        .p-note-2{
            font-size: 15px;
        }
    </style>
{% endblock %}





{% block content %}

<div class="container">
{# 成功添加图片格式 #}
{#    <img src="{{ STATIC_URL }}memoryImage/background/2cacad94-e2f6-48d9-8d08-9356267c7736.jpg" />#}
    <!-- 新增and编辑( Modal )  -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"
         data-backdrop="static">
        <div class="modal-dialog" style="width: 1000px;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="myModalLabel">添加记忆碎片</h4>
                </div>
                <form id="validate_form">
                    <div class="bk-form" style="width:900px;padding: 10px" id="validate_form">
                        <input type="hidden" id="memory_id" class="bk-form-input">
                        <div class="bk-form-item is-required">
                            <label class="bk-label" style="width:150px;">碎片标题</label>
                            <div class="bk-form-content" style="margin-left:150px;">
                                <input type="text" class="bk-form-input" id="memory_title" name="memory_title"
                                       placeholder="请输入碎片标题">
                            </div>
                        </div>
                        <div class="bk-form-item is-required">
                            <label class="bk-label" style="width:150px;">碎片主体</label>
                            <div class="bk-form-content" style="margin-left:150px;">
                                <div id="editor3_demo1" style="width:730px;height:600px;">
                                    <div id="myEditor" style="width:730px;height:600px;" name="myEditor">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="bk-form-item is-required">
                            <label class="bk-label" style="width:150px;">印象深度</label>
                            <div class="bk-form-content" style="margin-left:150px;">
                                <select name="" id="memory_level" class="bk-form-select">
                                    <option value=1>平平淡淡</option>
                                    <option value=2>较为触动</option>
                                    <option value=3>难以忘怀</option>
                                    <option value=4>不愿忘记</option>
                                </select>
                            </div>
                        </div>

                        <div class="bk-form-item is-required" style="display: none">
                            <label class="bk-label" style="width:150px;">生成日期</label>
                            <div class="bk-form-content" style="margin-left:150px;">
                                <input type="text" id="create_time" name="create_time">
                            </div>
                        </div>
                        <div class="bk-form-item is-required" style="display: none">
                            <label class="bk-label" style="width:150px;">锁存</label>
                            <div class="bk-form-content" style="margin-left:150px;">
                                <input type="checkbox" id="status">
                            </div>
                        </div>
                        <div class="bk-form-item is-required lock-checkbox">
                            <label class="bk-label" style="width:150px;">锁存结束日期</label>
                            <div class="bk-form-content" style="margin-left:150px;">
                                <input type="text" class="bk-form-input daterangepicker_demo bk-valid" id="end_time"
                                       name="end_time" placeholder="选择日期...">
                            </div>
                        </div>
                    </div>
                </form>
                <div class="modal-footer">
                    <button type="button" class="bk-button bk-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="bk-button bk-primary" onclick="saveMemory()">保存</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>



    <div class="row">
        <!-- 占位row -->
        <div class="row" style="height: 10px">
        </div>
        <!-- end 占位row -->

        <div class="row">
            <!-- 左侧导航栏 -->

            <div class="nav-left col-md-3">
                <div class="metismenu" id="vertical_nav11" style="width:250px;">
                    <aside class="sidebar" style="width:250px;">
                        <nav class="sidebar-nav">
                            <ul class="metismenu" id="menu">

                            </ul>
                        </nav>
                    </aside>
                </div>
            </div>


            <!-- 右侧展示区域 -->
            <div class="show-area col-md-6">
                <div class="show-memory-none" style="text-align: center; margin-top: 200px;">
                    <p class="p-note-1 p1">今日又有何事值得留念？</p>
                    <p class="p-note-1 p2">愿你将记忆化为小小的碎片，留在时间之中</p>
                    <p class="p-note-1 p3">凝作不可磨灭的记忆</p>
                    <button class="mybutton1" type="button" data-toggle="modal" data-target="#myModal" style="margin-top: 80px;">
                        创建记忆碎片
                    </button>
                </div>
                <div class="row">
                    <div id="show-memory-title"></div>
                    <div class="memory-content">
                        <div id="show-memory-notes"></div>
                        <div id="show-memory-content"></div>
                    </div>
                    <div id="show-memory-footer">
                        <div id="edit-memory"></div>
                    </div>
                </div>
            </div>

            <div class="right-button-area col-md-2" style="padding: 20px;margin-left: 100px">
                <div class="row" style="margin-bottom: 10px;">
                    <button id="add-general-memory" type="button" class="mybutton1" data-toggle="modal" data-target="#myModal">
                        <span class="glyphicon glyphicon-plus"></span>
                        创建记忆碎片
                    </button>
                </div>
                <div class="row">
                    <button id="add-locked-memory" type="button" class="mybutton1" data-toggle="modal" data-target="#myModal">
                        <span class="glyphicon glyphicon-lock"></span>
                        创建锁存碎片
                    </button>
                </div>
                <div class="row text-right" style="text-align: center; margin: 100px 80px 0 0; display: none">
                    <p class="p-note-2 p4">时间刻下的记忆</p>
                    <p class="p-note-2 p5">即便尝试改变</p>
                    <p class="p-note-2 p6">也会留下岁月的痕迹</p>
                </div>
            </div>

        </div>



    </div>


</div>

{% endblock %}



{% block extra_block %}
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/daterangepicker-2.0.5/moment.min.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/daterangepicker-2.0.5/daterangepicker.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/metisMenu-2.6.0/js/metisMenu.min.js"></script>



    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/wangEditor-2.1.22/dist/js/wangEditor.min.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/select2-3.5.2/select2.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/bkSwitcher-1.0/js/bkSwitcher.js"></script>
    <script src="https://magicbox.bk.tencent.com/static_api/v3/assets/validate-1.14.0/js/jquery.validate.js"></script>
    <script>


        var memory_list = [];// 所有记忆碎片列表
        var memory_classification = {}; // 记忆碎片分类信息

        var nav_flash = -1;//记录导航栏操作次数 该变量是为了使得用户添加数据后重新刷新导航栏，而不是整个页面刷新


        $('#status').bkSwitcher({
            size: 'large'
        });

        //editor3_demo1_js_start
        var editor = new window.wangEditor('editor3_demo1');
        {#editor.config.uploadImgUrl = '{{ SITE_URL }}memory_storage/upload_img/';#}
        {#editor.config.uploadParams = {#}
        {#    'belonging_user': 1,#}
        {#    'csrfmiddlewaretoken': "{{ csrf_token }}"#}
        {# };#}
        {#editor.config.uploadImgFileName = 'myFileName';#}


        editor.config.height = 600;
        {#editor.config.hideLinkImg = true;#}
        editor.config.uploadImgShowBase64 = true;

        {#editor.config.uploadImgFns.onload = ((resultText, xhr) => {#}
        {#    var resultTextBox = JSON.parse(resultText);#}
        {#    var resultText = resultTextBox.url;#}
        {#    console.log(resultText);#}
        {#    this.editor.command(null, 'InsertImage', resultText);#}
        {# });#}

        {#editor.config.customUploadImg = function (resultFiles, insertImgFn) {#}
        {#     // resultFiles 是 input 中选中的文件列表#}
        {#        // insertImgFn 是获取图片 url 后，插入到编辑器的方法#}
        {#    console.log(resultFiles[0]);#}
        {#    // 上传图片，返回结果，将图片插入到编辑器中#}
        {#    //insertImgFn(imgUrl)#}
        {# }; #}
        {##}
        editor.create();

        //editor3_demo1_js_end

        // 选择单个日期


        $('#create_time').daterangepicker({
            locale: {
                format: 'YYYY-MM-DD'
            },
            autoApply: false, //选择日期后自动设置值
            singleDatePicker: true //单选选择一个日期
        });

        $('#end_time').daterangepicker({
            locale: {
                format: 'YYYY-MM-DD'
            },
            autoApply: false, //选择日期后自动设置值
            autoUpdateInput: true,
            drops: "up",
            singleDatePicker: true //单选选择一个日期
        });


        /**
         * 校验合法
         */
        $('#validate_form').validate({
            ignore: '.ignore',
            errorElement: 'div', //错误信息的容器
            errorClass: 'is-danger',
            errorPlacement: function (error, element) {
                error.addClass('bk-form-tip').insertAfter(element)
            },
            validClass: "bk-valid",
            //验证规则
            rules: {
                memory_title: {
                    required: true,
                },
                memory_level: {
                    required: true,
                },
                {#end_time: {#}
                {#    required: true,#}
                {# },#}
            },
            //错误提示信息
            messages: {
                memory_title: "<p class='bk-tip-text'>请为记忆碎片加上主题</p>  ",
                memory_level: "<p class='bk-tip-text'>请选择印象深度</p>  ",
                end_time: "<p class='bk-tip-text'>请选择锁存结束日期</p>  ",
            }
        });


        // 刚开始调用一次showAllMemoryInNav()
        showAllMemoryInNav();

        // 采用函数方式只是使得用户添加数据后重新刷新导航栏，而不是整个页面刷新
        // 或许有更好的办法，但我不知道

         /**
         * 加载侧边导航栏
         * 获取所有记忆碎片
         */
        function showAllMemoryInNav(){

            nav_flash++;
            //console.log(GetQueryString('user_id'));

            if (nav_flash > 0 ){
                // 为了使得用户添加数据后重新刷新导航栏，而不是整个页面刷新
                // empty()先清空，再调用metisMenu('dispose')让js失效
                // 不然疑似会导致下一次js启动失败
                $("#menu").empty().metisMenu('dispose');
            }

            $.ajax({
            url: '{{ SITE_URL }}memory_storage/get_memory_info/',
            method: 'POST',
            data: {
                'user_id': GetQueryString('user_id'),
                'csrfmiddlewaretoken': "{{ csrf_token }}"
            },
            dataType: 'JSON',
            success: function (response) {
                //console.log(response);
                memory_list = response.data;

                memory_classification = eval(response.classification);
                //测试输出
                console.log(memory_list);
                //console.log(memory_classification);
                //console.log(typeof (memory_classification))

                // 进行字符串拼接
                html = "";
                html += '<li>'+
                        '<a href="javascript:;">'+
                        '<span class="glyphicon glyphicon-th-list"></span>'+
                        '<span class="sidebar-nav-item">我的记忆碎片</span>'+
                        '</a>'+
                        '</li>';

                for( var year in memory_classification ){
                    html += '<li id="' + 'year-' + year + '">';
                    html += '<a class="has-arrow" href="javascript:;">';
                    html += '<span class="glyphicon glyphicon-star"></span>';
                    html += '<span class="sidebar-nav-item">' + year + ' 年</span>';
                    html += '</a>';
                    html += '<ul>';
                    //console.log(html);

                    for( var month in memory_classification[year] ) {
                        //console.log(month);
                        html += '<li id="' + 'month-' + month + '">'
                            + '<a class="has-arrow" href="javascript:;">'
                            + '<span class="glyphicon glyphicon-star-empty"></span>'
                            + '<span class="sidebar-nav-item">' + month + ' 月</span>'
                            + ' </a>'
                            + '<ul>';

                        for ( var day in memory_classification[year][month]) {
                            html += '<li id="' + 'day-' + day + '">'
                                + '<a class="has-arrow" href="javascript:;">'
                                + '<span class="glyphicon glyphicon-minus"></span>'
                                + '<span class="sidebar-nav-item">' + day + ' 日</span>'
                                + ' </a>'
                                + '<ul>';

                            for ( var memory_index in memory_classification[year][month][day]) {
                                let memory_id = memory_classification[year][month][day][parseInt(memory_index)];

                                //获得标题和结束时间
                                let info = getMemoryTitleAndEndTime(memory_id);
                                //当前时间
                                let now = moment().format('YYYY-MM-DD');
                                let memory_icon_class = "";
                                if( info[1] > now ){
                                    memory_icon_class = "glyphicon glyphicon-lock";
                                }

                                html += '<li id="' + 'memory_id-' + memory_id + '">'
                                    + '<a href="javascript:;" onclick="showMemory(' + memory_id +  ')"  >'
                                    + `<span class="${memory_icon_class}"></span>`
                                    + '<span class="sidebar-nav-item">' + info[0] + '</span>'
                                    + '</a>'
                                    + '</li>'
                             }

                            html += '</ul>' + '</li>';
                         }

                        html += '</ul>' + '</li>';
                    }

                    html += '</ul>' + '</li>';
                }

                //运行左侧导航栏js
                $("#menu").append(html).metisMenu();
            }
        });
        }


        /**
         * 取得记忆碎片的标题和锁存结束时间，用于左边导航栏展示
         */
        function getMemoryTitleAndEndTime(memory_id) {
            for( var memory of memory_list ){
                if(memory.memory_id === memory_id){
                    return [memory.memory_title, memory.end_time];
                }
            }
        }

        /**
         * 展示记忆碎片
         */
        var haveMemory = 0;// 用于表示上一次是否加载了记忆碎片
        function showMemory(memory_id) {
            //当前时间
            let now = moment().format('YYYY-MM-DD');

            // 无记忆碎片加载时候的信息隐藏
            $(".show-memory-none").hide();
            // 锁存未结束信息移除
            $("#show-lockedInfo").remove();
            // 显示主体
            $(".memory-content").show();
            if( haveMemory === 1){
                // 如果已经加载过一个碎片，即页面的memory-content中有内容
                // 则先清空区域，以不影响下一个碎片的展示
                $("#show-lockedInfo").remove();
                $("#show-memory-title").empty();
                $("#show-memory-notes").empty();
                $("#show-memory-content").empty();
                $("#show-memory-create_time").empty();
                $('#edit-memory').empty();
                haveMemory = 0;
            }
            for( var memory of memory_list){
                if(memory.memory_id === memory_id){

                    haveMemory = 1;
                    // 如果锁存时间没有结束
                    if(memory.end_time > now){
                        let lockedInfo = '';
                        lockedInfo = '<div id="show-lockedInfo">'+
                                '<span class="glyphicon glyphicon-lock" style="font-size: 15em; "></span>'+
                                '<p style="font-size: 3em;">锁存时间未到不能偷看哦</p>'+
                                '<p style="font-size: 2em;">锁存结束时间' + memory.end_time + '</p>'+
                                '</div>';
                        // 加入相应提示信息
                        $(".show-area").append(lockedInfo);
                        $(".memory-content").hide();
                        haveMemory = 0;
                        return false;
                    }

                    // 展示记忆碎片内容
                    $("#show-memory-title").append(memory.memory_title);
                    let notes = '<span style="margin-right: 20px">创建日期: ' + memory.create_time + '</span>'
                              + '<span>重要等级: ' + memory.memory_level + '</span>';
                    $("#show-memory-notes").append(notes);

                    $("#show-memory-content").append(memory.memory_content);

                    var edit_button = '';
                    edit_button =
                            '<a class="bk-icon-button bk-warning bk-button-mini" onclick="editMemoryForm(' + memory_id + ')" title="编辑">' +
                            '<i class="bk-icon icon-file bk-icon"></i>' +
                            '<i class="bk-text">编辑</i>' +
                            '</a>';

                    $('#edit-memory').append(edit_button);
                }
            }

        }

        /**
         * 保存记忆碎片
         */
        function saveMemory() {
            //console.log("saveMemory()");
            //let create_time = $('#create_time').val();
            let end_time = $('#end_time').val();
            var switcher_status = $('#status').data('bkSwitcher');
            //当前时间
            var now = moment().format('YYYY-MM-DD hh:mm:ss');

            if( !end_time || end_time === "1999-01-01 00:00:00"){
                // 不是锁存记忆
               end_time = "1999-01-01 00:00:00";

            }else {
                // 用户选择了锁存记忆
                end_time = end_time + " 23:59:59";
                let active = true;
                switcher_status.setStatus(active);

                if (now >= end_time) {
                    new bkMessage({
                        message: "锁存结束日期不能小于创建日期哦",
                        theme: 'error',
                        delay: 3000
                    });
                    return false
                 }
            }

            if (!editor.$txt.text()) {
                new bkMessage({
                    message: "请描绘一下今天的记忆吧",
                    theme: 'error',
                    delay: 3000
                });
                return false
            }

            if ($('#validate_form').valid()) {
                $.ajax({
                    url: '{{ SITE_URL }}memory_storage/save_memory_info/',
                    method: 'post',
                    data: {
                        'memory_title': $("#memory_title").val(),
                        'memory_content': editor.$txt.html(),
                        'memory_level': $('#memory_level').val(),
                        //'create_time': create_time,
                        'end_time': end_time,
                        'status': switcher_status.getStatus(),
                        // 不同用户登录功能待开发 默认为1号用户
                        'user_id': GetQueryString('user_id'),
                        'memory_id': $('#memory_id').val(),
                        'csrfmiddlewaretoken': "{{ csrf_token }}"
                    },
                    success: function (response) {
                        console.log(response);
                        if (response['result']) {
                            new bkMessage({
                                message: response['message'],
                                theme: 'success'
                            });
                            $('#myModal').modal('hide');

                            showAllMemoryInNav();
                            //awardTable.ajax.reload(null, false)
                        } else {
                            // 失败处理
                            new bkMessage({
                                message: response['message'],
                                theme: 'error',
                                delay: 3000
                            });
                            $('#myModal').modal('hide');
                            //awardTable.ajax.reload(null, false)
                        }
                    }
                })
            }
        }

        /**
         * 当模态框关闭时
         */
        $('#myModal').on('hide.bs.modal', function () {
            document.getElementById("validate_form").reset();
            $("#validate_form").validate().resetForm();
            $("#memory_title").val("");
            $("#memory_id").val("");
            editor.clear();
            $('#memory_level').val(1);
            $('#create_time').val("");
            $('#end_time').val("");
            var active = false;

            var switcher = $('#status').data('bkSwitcher');
            switcher.setStatus(active);
        });

        /**
         * 编辑我的记忆
         */
        function editMemoryForm(memory_id) {
            for( var memory of memory_list) {
                if(memory.memory_id === memory_id){
                    $("#myModalLabel").text("修改记忆碎片");
                    $('#myModal').modal('show');
                    $("#memory_id").val(memory.memory_id);
                    $("#memory_title").val(memory.memory_title);
                    editor.$txt.html(memory.memory_content);
                    $('#memory_level').val(memory.memory_level);

                    //$('#create_time').val(memory.create_time);
                    $(".lock-checkbox").hide();

                    var switcher = $('#status').data('bkSwitcher');
                    if(memory.status === 0){
                        switcher.setStatus(false);
                    }else {
                        switcher.setStatus(true);
                    }
                }
            }
        }


        // 按钮选择添加普通记忆碎片
        // 作用：根据按钮的种类，修改弹出的模态框
        $('#add-general-memory').click(function () {
            $("#myModalLabel").text("添加记忆碎片");
            $('#end_time').val("");
            $(".lock-checkbox").hide();

            {#let switcher = $('#status').data('bkSwitcher');#}
            {#switcher.setStatus(false);#}
         });

        $('.mybutton1').click(function () {
            $("#myModalLabel").text("添加记忆碎片");
            $('#end_time').val("");
            $(".lock-checkbox").hide();

            {#let switcher = $('#status').data('bkSwitcher');#}
            {#switcher.setStatus(false);#}
        });

        // 按钮选择添加锁存记忆碎片
        // 作用：根据按钮的种类，修改弹出的模态框
        $('#add-locked-memory').click(function () {
           $("#myModalLabel").text("添加锁存碎片");
           $(".lock-checkbox").show();

           {#let switcher = $('#status').data('bkSwitcher');#}
           {#switcher.setStatus(true);#}
        });


        /**
         * 一些js控制的动作
         */
        $(".text-right").fadeIn(2000);

        $(".p1").hide().fadeIn(1500);
        $(".p2").hide().fadeIn(2500);
        $(".p3").hide().fadeIn(3500);
        $(".mybutton1").hide().fadeIn(5000);


</script>
{% endblock %}